package com.usian.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.util.JsonUtils;
import com.usian.model.search.dtos.UserSearchDto;
import com.usian.search.entity.ApAssociateWords;
import com.usian.search.mapper.ApAssociateWordsMapper;
import com.usian.search.model.Trie;
import com.usian.search.service.IApAssociateWordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 联想词表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-10-19
 */
@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper, ApAssociateWords> implements IApAssociateWordsService {

    /**
     联想词
     @param dto
     @return
     */
    @Override
    public List<ApAssociateWords> search(UserSearchDto dto) {
//        模糊查询数据
        IPage<ApAssociateWords> page = new Page<>(1,dto.getPageSize());
        QueryWrapper<ApAssociateWords> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(ApAssociateWords::getAssociateWords,dto.getSearchWords());
        IPage<ApAssociateWords> iPage = this.page(page, queryWrapper);
        return iPage.getRecords();
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    String PRE_FIX = "ld:search:associate:";
    /**
     联想词2222222222
     @param dto
     @return
     */
    @Override
    public List<ApAssociateWords> searchV2(UserSearchDto dto) {
        //尝试从redis中获取联想词列表
        String key=PRE_FIX+"list";
        String associateListStr = redisTemplate.opsForValue().get(key);
        List<ApAssociateWords> list = null;
        if (StringUtils.isEmpty(associateListStr)){
            //redis没有存入联想词,查询数据库，并缓存到redis中
            list = this.list();
            redisTemplate.opsForValue().set(key, JsonUtils.toString(list));
        }else {
            //解析redis联想词
            list = JsonUtils.toList(associateListStr,ApAssociateWords.class);
        }
        //构建trie树
        Trie trie = new Trie();
        for (ApAssociateWords apAssociateWords : list) {
            trie.insert(apAssociateWords.getAssociateWords());
        }
        //查询搜索关键字相关的联想词列表
        List<String> list1 = trie.startWith(dto.getSearchWords());
        //封装联想词对象集合
        List<ApAssociateWords> apAssociateWordsList = new ArrayList<>();
        for (String str : list1) {
            ApAssociateWords apAssociateWords = new ApAssociateWords();
            apAssociateWords.setAssociateWords(str);
            apAssociateWordsList.add(apAssociateWords);
        }
        return apAssociateWordsList;
    }
}
